package lcof;

public class isValidSudoku {
    int[][] index = new int[][]{{0, 0}, {0, 3}, {0, 6},
            {3, 0}, {3, 3}, {3, 6},
            {6, 0}, {6, 3}, {6, 6}};


    public boolean isValidSudoku(char[][] board) {
        //行
        for (int i = 0; i < 9; i++) {
            char[] row = board[i];
            int temp = 0;
            for (char c : row) {
                if (c == '.') {
                    continue;
                }
                int num = c - '0';
                if (!allow(temp, num)) {
                    return false;
                }
                temp = temp | (1 << num);
            }
        }
        //列
        for (int i = 0; i < 9; i++) {
            int temp = 0;
            for (int j = 0; j < 9; j++) {
                char c = board[j][i];
                if (c == '.') {
                    continue;
                }
                int num = c - '0';
                if (!allow(temp, num)) {
                    return false;
                }
                temp = temp | (1 << num);

            }
        }
        //子方块
        for (int[] arr : index) {
            int x = arr[0];
            int y = arr[1];
            int temp = 0;
            for (int k = 0; k < 3; k++) {
                for (int i = 0; i < 3; i++) {
                    char c = board[x + k][y + i];
                    if (c == '.') {
                        continue;
                    }
                    int num = c - '0';
                    if (!allow(temp, num)) {
                        return false;
                    }
                    temp = temp | (1 << num);
                }
            }
        }
        return true;
    }

    /**
     * init_temp = 0
     *
     * @param temp 标记位
     * @param num  当前数字
     */
    private boolean allow(int temp, int num) {
        if ((temp & (1 << num)) != 0) {
            return false;
        }
        return true;
    }
}
